package com.cht.commonUtil.mail;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.enums.RecipientType;
import com.cht.commonUtil.widgets.Widgets;

public class SendMail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/text");
		
		String res = "";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String subsysId = request.getParameter("subsysId");
		int tarDeliverySN = Integer.parseInt(request.getParameter( "tarDeliverySN" ) );
		int mailType =  Integer.parseInt(request.getParameter( "maileType" ) );
		String localSystemName = request.getParameter("localSystemName");
		String msgBody = request.getParameter("msgBody");
		String subject = request.getParameter("subject");
		try {
			conn = Widgets.getConn();
			
			List<String[]> tos = Widgets.getRecipient(mailType,RecipientType.TO,subsysId);	//部署通知正本不需要這個參數，隨意寫入一整數
			List<String[]> ccs = Widgets.getRecipient(mailType,RecipientType.CC,subsysId);
			List<String[]> bccs = Widgets.getRecipient(mailType,RecipientType.BCC,subsysId);
			//信件主旨
			subject = localSystemName+subject+tarDeliverySN;
			Widgets.sendMailMain(tos,ccs,bccs,subject,msgBody);
			
			for(int i=0;i<ccs.size();i++) {
				res += "CCS:"+ccs.get(i)[1];
			}
			
			for(int i=0;i<bccs.size();i++) {
				res += "BCCS:"+bccs.get(i)[1];
			}
			for(int i=0;i<tos.size();i++) {
				res += "TO:"+tos.get(i)[1];
			}
			
		} catch(Exception e) {
			res = Widgets.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (Exception e) { e.printStackTrace(); }
		}
		response.getWriter().write(res);
	}
}
